<?php

namespace App\HttpController\Admin;

use App\Common\Session;
use EasySwoole\Session\Context;
use EasySwoole\EasySwoole\Config;
use EasySwoole\Http\AbstractInterface\Controller;

use App\Common\Tools;

class Base extends Controller
{
    /**
     * 
     * @param string|null $action
     * @return bool|null
     */
    public function onRequest(?string $action): ?bool
    {
        $user = $this->session()->get('adminUser');
        if (!$user || ($user['expire'] != 'never' && $user['expire'] < time())) {
            $this->session()->del('adminUser');
            $this->response()->redirect("/admin/login.html");
            return false;
        } else {
            return true;
        }
    }

    /**
     * 此控制器抛异常时会执行此方法
     *
     * @param \Throwable $throwable
     * @throws \Throwable
     */
    public function onException(\Throwable $throwable): void
    {
        if (in_array($throwable->getCode(), [404, 405])) {
            Tools::json($this->response(), $throwable->getCode(), [], $throwable->getMessage());
        } else {
            parent::onException($throwable); // TODO: Change the autogenerated stub
        }
    }

    // 封装session方法
    protected function session(): ?Context
    {
        $sessionName = Config::getInstance()->getConf('SESSION.name');
        // 封装一个方法，方便我们快速获取 session context
        $sessionId = $this->request()->getAttribute($sessionName);
        return Session::getInstance()->create($sessionId);
    }
}
